<template>
  <PublicPage
      pageBgcolor="#ffffff"
      custoNav
      class="edit-template"
  >
    <!-- 自定义头部-->
    <HeadNav
        slot="headNav"
        borderType
        showNav
        :pageName="pageName+'运费模板'"
        :customBack="goBackFn"
        @back="goBackFn"
    />
    <!-- 模板名称区域 -->
    <view class="template-name">
      <view class="txt">模板名称</view>
      <input
          :value="detail.name"
          placeholder="输入模板名称"
          placeholder-style="#C8C9CC"
          maxlength="10"
          class="input-view"
          @input="inputName"
      />
    </view>
    <!-- 添加运费规则区域 -->
    <view class="create-button-wrap">
      <button class="button" @click="openArea">+添加运费规则</button>
    </view>
    <!-- 滚动区域 -->
    <scroll-view scroll-y class="scroll-wrap">
      <!-- 运费规则区域 -->
      <view v-for="(item, index) in detail.goodsFreightTemplateRuleAddVOList" :key="index" class="wrap1">
        <view class="area-content" @click="areaOpen(item,index)">
          <view class="area">
            <text v-for="(it,idx) in item.freightTemplateConfigurationReqVO._areas" :key="idx" class="viceColorN8">
              {{it.provinceStr}}
              <text v-if="!it.hasAll" class="viceColor">
                (
                <text v-for="(sub,ix) in it.citiesStr" :key="ix">
                  {{sub}}{{(ix+1)<(it.citiesStr.length)?'/':''}}
                </text>
                )
              </text>
              {{(idx+1)<(item.freightTemplateConfigurationReqVO._areas.length)?'、':''}}
            </text>
          </view>
          <view class="iconfont icon-arrow_right"></view>
        </view>
        <view class="rule-content" @click="openSetItem(item)">
          <view class="rule-txt">运费规则</view>
          <!-- 固定运费 -->
          <view v-if="item.freightTemplateConfigurationReqVO.type==0" class="rule-detail">
            固定运费{{item.freightTemplateConfigurationReqVO.fixedPrice}}元
            {{item.freightTemplateConfigurationReqVO.isFree==1?(`，满${item.freightTemplateConfigurationReqVO.conditionType==1?`${item.freightTemplateConfigurationReqVO.conditionNumber}件`:`${item.freightTemplateConfigurationReqVO.conditionMoney}元`}包邮`):''}}
          </view>
          <view v-else class="rule-detail">
            {{item.freightTemplateConfigurationReqVO.firstCompany}}件内运费{{item.freightTemplateConfigurationReqVO.firstPrice}}元，每增加{{item.freightTemplateConfigurationReqVO.continuedCompany}}件增加运费{{item.freightTemplateConfigurationReqVO.continuedPrice}}元
            {{item.freightTemplateConfigurationReqVO.isFree==1?(`，满${item.freightTemplateConfigurationReqVO.conditionType==1?`${item.freightTemplateConfigurationReqVO.conditionNumber}件`:`${item.freightTemplateConfigurationReqVO.conditionMoney}元`}包邮`):''}}
          </view>
          <view class="iconfont icon-arrow_right"></view>
        </view>
      </view>
      <!-- 不发货地区区域 -->
      <view class="wrap2">
        <view class="header">不发货地区</view>
        <view class="center" @click="noOpenArea">
          <view v-if="detail.noDeliveryVOList.length" class="u-flex-1">
            <text v-for="(item,index) in noDelivery._areas" :key="index" class="txt">
              {{item.provinceStr}}
              <text v-if="!item.hasAll" class="viceColor">
                (
                <text v-for="(sub,ix) in item.citiesStr" :key="ix">
                  {{sub}}{{(ix+1)<(item.citiesStr.length)?'/':''}}
                </text>
                )
              </text>
              {{(index+1)<(noDelivery._areas.length)?'、':''}}
            </text>
          </view>
          <view v-else class="u-flex-1 txt">请选择</view>
          <view class="iconfont icon-arrow_right"></view>
        </view>
        <view class="bottom">未设置的城市将默认包邮</view>
      </view>
    </scroll-view>
    <!-- 底部按钮 -->
    <view class="footer-button u-flex">
      <button :disabled="hasSubmit" class="button" @click="onSubmit">保存设置</button>
    </view>
    <!-- 分割线 -->
    <!-- 选择地址 -->
    <u-popup
        v-model="dlAreaPopup"
        mode="bottom"
        height="80%"
        safe-area-inset-bottom
        border-radius="24"
        @maskClick="closeArea"
    >
      <view class="area-popup">
        <view class="header">
          <text class="txt">选择城市</text>
          <view class="iconfont icon-close" @click="closeArea"></view>
        </view>
        <scroll-view scroll-y class="area-collapse">
          <view
              v-for="(item,index) in areaList"
              :key="item.id"
              class="collapse-item"
          >
            <!-- 省 -->
            <view class="p-item">
              <view class="p-lt" @click="provinceChecked(item)">
                <view
                    class="iconfont p-checkbox"
                    :class="{
                      'icon-checkbox p-checkbox-empty':!item.checkeds.length,
                      'icon-reboot_color icon-checked':item.indeterminate,
                      'icon-checkbox_fill icon-checked':item.allChecked&&item.checkeds.includes(timeTamp),
                      'icon-checkbox_fill disabled-checkbox':item.allChecked&&!item.checkeds.includes(timeTamp)
                    }"
                ></view>
                <view class="p-name">{{item.name}}</view>
              </view>
              <view class="p-rt" @click="changeCollapse(item,index)">
                <view class="iconfont icon-arrow_right" :class="{'icon-arrow_right_active':item.show}"></view>
              </view>
            </view>
            <!-- 省 -->
            <!-- 分割线 -->
            <!-- 市 -->
            <view class="c-list-body" :style="{height:item.show?item.height+'px':'0'}">
              <view class="c-list" :id="'c_'+item.id">
                <view
                    v-for="(sub,subIx) in item.getCityVOList"
                    :key="sub.id"
                    class="c-item"
                    @click="cityChecked(sub,subIx,item,index)"
                >
                  <view
                      class="iconfont c-checkbox"
                      :class="{
                        'icon-checkbox c-checked-empty':!sub.checked,
                        'icon-checkbox_fill icon-checked':sub.checked&&sub.checked===timeTamp,
                        'icon-checkbox_fill disabled-checkbox':sub.checked&&sub.checked!==timeTamp,
                      }"
                  ></view>
                  <view class="c-name">{{sub.name}}</view>
                </view>
              </view>
            </view>
            <!--  市 -->
          </view>
        </scroll-view>
        <view class="area-footer">
          <button hover-class="none" class="lf-btn" @click="allSelected">
            <view
                class="iconfont icon"
                :class="{
                  'icon-checkbox':(areaType===0&&!editConfig._allSelected)||(areaType===1&&!noDelivery._allSelected),
                  'icon-checkbox_fill':(areaType===0&&editConfig._allSelected)||(areaType===1&&noDelivery._allSelected)
                }"
            ></view>
            <text>全选</text>
          </button>
          <button class="rt-btn" @click="openSetting">
            选择地址（{{areaType===0?editConfig._selectedNum:noDelivery._selectedNum}}）
          </button>
        </view>
      </view>
    </u-popup>
    <!-- 选择地址 -->
    <!-- 分割线 -->
    <!-- 运费设置 -->
    <u-popup
        v-model="dlSettPopup"
        mode="bottom"
        height="80%"
        safe-area-inset-bottom
        border-radius="24"
        @maskClick="()=>dlSettPopup=false"
    >
      <view class="setting-popup">
        <view class="header">
          <text class="txt">运费设置</text>
          <view class="iconfont icon-close" @click="()=>dlSettPopup=false"></view>
        </view>
        <view class="freight-type">
          <view class="type-item" @click="changType(0)">
            <view
                class="iconfont"
                :class="{
                  'icon-checkbox_fill':editConfig.type==0,
                  'icon-checkbox':editConfig.type==1
                }"
            ></view>
            <text class="txt">固定运费</text>
          </view>
          <view class="type-item" @click="changType(1)">
            <view
                class="iconfont"
                :class="{
                  'icon-checkbox_fill':editConfig.type==1,
                  'icon-checkbox':editConfig.type==0
                }"
            ></view>
            <text class="txt">按件计费</text>
          </view>
        </view>
        <scroll-view scroll-y class="scroll-setting">
          <!-- 固定运费 -->
          <view v-if="editConfig.type==0" class="type0-wrap">
            <view class="fz-14 viceColorN8">运费金额</view>
            <view class="input-wrap">
              <input
                  :value="editConfig.fixedPrice"
                  type="number"
                  placeholder="请输入"
                  placeholder-style="#CCCCCC"
                  class="input"
                  maxlength="9"
                  @input="(e)=>changeInput(e, 'fixedPrice')"
              />
              <text class="txt">元</text>
            </view>
          </view>
          <!-- 按件计费 -->
          <view v-else class="type1-wrap">
            <view class="type1-item">
              <!-- 首个件 -->
              <view class="input-wrap">
                <input
                    :value="editConfig.firstCompany"
                    type="number"
                    placeholder="请输入"
                    placeholder-style="#CCCCCC"
                    class="input"
                    maxlength="9"
                    @input="(e)=>changeInput(e, 'firstCompany')"
                />
                <text class="txt">件</text>
              </view>
              <text class="viceColorN8 fz-14 u-m-l-8">内(含)，</text>
              <text class="type1-txt">运费</text>
              <!-- 首个元 -->
              <view class="input-wrap">
                <input
                    :value="editConfig.firstPrice"
                    type="number"
                    placeholder="请输入"
                    placeholder-style="#CCCCCC"
                    class="input"
                    maxlength="9"
                    @input="(e)=>changeInput(e, 'firstPrice')"
                />
                <text class="txt">元</text>
              </view>
            </view>
            <view class="type1-item">
              <text class="viceColorN8 fz-14 u-m-r-8">每增加</text>
              <!-- 每增加件 -->
              <view class="input-wrap">
                <input
                    :value="editConfig.continuedCompany"
                    type="number"
                    placeholder="请输入"
                    placeholder-style="#CCCCCC"
                    class="input"
                    maxlength="9"
                    @input="(e)=>changeInput(e, 'continuedCompany')"
                />
                <text class="txt">件</text>
              </view>
              <text class="type1-txt">运费增加</text>
              <!-- 每增加元 -->
              <view class="input-wrap">
                <input
                    :value="editConfig.continuedPrice"
                    type="number"
                    placeholder="请输入"
                    placeholder-style="#CCCCCC"
                    class="input"
                    maxlength="9"
                    @input="(e)=>changeInput(e, 'continuedPrice')"
                />
                <text class="txt">元</text>
              </view>
            </view>
          </view>
          <!-- 指定条件包邮 -->
          <view class="spec-req-wrap">
            <view class="switch-wrap">
              <view class="switch-txt">指定条件包邮</view>
              <u-switch
                  v-model="editConfig.isFree"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#E44435"
                  size="44"
                  @change="changeFree"
              />
            </view>
            <!-- 指定条件包邮--isFree === 1 -->
            <view v-if="editConfig.isFree" class="is-free-wrap">
              <view class="free-item">
                <view
                    class="iconfont"
                    :class="{
                      'icon-checkbox_fill':editConfig.conditionType==1,
                      'icon-checkbox':editConfig.conditionType==2
                    }"
                    @click="changeConType(1)"
                ></view>
                <text class="txt">订单满</text>
                <view class="input-wrap">
                  <input
                      :value="editConfig.conditionNumber"
                      type="number"
                      placeholder="请输入"
                      placeholder-style="#CCCCCC"
                      class="input"
                      maxlength="9"
                      @input="(e)=>changeInput(e, 'conditionNumber')"
                  />
                  <text class="input-txt">件</text>
                </view>
                <text class="txt">可包邮</text>
              </view>
              <view class="free-item">
                <view
                    class="iconfont"
                    :class="{
                      'icon-checkbox_fill':editConfig.conditionType==2,
                      'icon-checkbox':editConfig.conditionType==1
                    }"
                    @click="changeConType(2)"
                ></view>
                <text class="txt">订单满</text>
                <view class="input-wrap">
                  <input
                      :value="editConfig.conditionMoney"
                      type="number"
                      placeholder="请输入"
                      placeholder-style="#CCCCCC"
                      class="input"
                      maxlength="9"
                      @input="(e)=>changeInput(e, 'conditionMoney')"
                  />
                  <text class="txt">元</text>
                </view>
                <text class="txt">可包邮</text>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="setting-footer">
          <button class="button" @click="submitSetting">确定</button>
        </view>
      </view>
    </u-popup>
    <!-- 确认退出确认框 -->
    <u-modal v-model="dlModal" :show-title="false" :show-confirm-button="false">
      <view class="cancel-modal">
        <view class="fz-18 tc fw5 viceColorN8 linh-24">确认退出？</view>
        <view class="modal-cancel-content">当前模板有改动，是否保存再退出？</view>
        <view class="modal-button-wrap">
          <view class="button" @click="navigateBack">直接退出</view>
          <view class="button themeFontColor fw5" @click="onSubmit">保存并退出</view>
        </view>
      </view>
    </u-modal>
  </PublicPage>
</template>

<script>
import PublicPage from '@/components/publicPage/index.vue'
import HeadNav from '@/components/headNav/index.vue'
import freightApi from '@/api/freight.js'
import { isArray } from '@/utils/is.js'

export default {
  name: 'editTemplate',
  components: {
    PublicPage,
    HeadNav
  },
  data() {
    return {
      pageName: '新增',
      routeData: {}, // 路由参数
      detail: {
        noDeliveryVOList: [], // 不配送省编码 noDeliveryVOList = [{notCityIdList: [], notProvinceId: ''}]
        goodsFreightTemplateRuleAddVOList: [], // 运费规则数组 goodsFreightTemplateRuleAddVOList = [{freightTemplateConditionReqVOList: [{cityIdList: [], provinceId: ''}], freightTemplateConfigurationReqVO: {}}]
        name: '', // 名称
      },
      goodsFreightTemplateVOList: [], // 用于新增\修改的VO(过滤前端自定义的字段)
      copyName: '', // 模板名称副本--退出时的比较
      copyNoDelivery: '', // 不发货地区副本--退出时的比较
      copyGoodsFreightTemplate: '', // 运费规则副本--退出时的比较
      editConfig: {
        conditionMoney: '', // 满足金额
        conditionNumber: '', // 满足件数
        conditionType: 0, // 指定条件（0.isFree为0 1.满足件数 2.满足金额)
        continuedCompany: '', // 续个(件)
        continuedPrice: '', // 续个(件)价格
        firstCompany: '', // 首个(件)
        firstPrice: '', // 首个(件)价格
        fixedPrice: '', // 固定价格
        isFree: 0, // 指定条件包邮 0:否 1：是
        type: 0, // 计费规则 0：固定运费 1：按件计费
        _areas: [], // {provinceStr: '', citiesStr: []}
        _selectedNum: 0, // 当前选市中的总条数
        _allSelected: false, // 当前全选中标识
        _isFirst: true, // 标识编辑时是否是第一次打开的(true时，计算当前的全选状态)
      },
      frIndex: -1, // 打开运费规则的下标
      areaIds: [], // 提交的选中的省市列表[{cityIdList: [], provinceId: ''}]
      areaType: 0, // 0表示运费规则打开的，1表示从不发货地区打开的
      noDelivery: { // 自定义不发货对象
        _areas: [], // // {provinceStr: '', citiesStr: []}
        timeTamp: Date.now(),
        _selectedNum: 0, // 当前选市中的总条数
        _allSelected: false, // 当前全选中标识
        _isFirst: true, // 标识编辑时是否是第一次打开的(true时，计算当前的全选状态)
      },
      copyNoDeliver: '', // 不发货地区的选中地区、总条数、全选标识副本
      dlAreaPopup: false, // 选择地址popup变量
      dlSettPopup: false, // 运费设置popup变量
      dlModal: false,
      areaList: [], // 地址列表
      copyAreaList: '', // 地址列表副本
      timeTamp: '', // 临时时间戳|运费规则templateRuleId
      hasSubmit: false, // 最后保存设置按钮的是否可点击
      allCities: 0, // 全部的城市数量
    }
  },
  onLoad(option) {
    this.routeData = option
    if (option.templateId) this.pageName = '编辑'
  },
  onShow() {
    if (this.routeData.templateId) this.hasSubmit = true
    this.getAreaList()
  },
  methods: {
    // 返回
    async goBackFn() {
      if (this.routeData.templateId) {
        if (this.detail.name !== this.copyName || JSON.stringify(this.detail.noDeliveryVOList) !== this.copyNoDelivery || JSON.stringify(this.goodsFreightTemplateVOList) !== this.copyGoodsFreightTemplate) {
          this.dlModal = true
        } else {
          this.navigateBack()
        }
      } else {
        this.navigateBack()
      }
    },
    // 获取地址列表
    getAreaList() {
      freightApi.areaList().then(({ data }) => {
        if (isArray(data)) {
          for (let i = 0, length = data.length; i < length; i++) {
            data[i].show = false // 是否展开市
            data[i].height = 0 // 市的高度
            data[i].checkeds = [] // 省的选中状态--临时时间戳|运费规则templateRuleId
            data[i].indeterminate = false // 市部分选中时，省半选中的状态
            data[i].allChecked = false // 市全部时，省全选中的状态
            if (isArray(data[i].getCityVOList)) {
              this.allCities += data[i].getCityVOList.length
              for (let j = 0, length = data[i].getCityVOList.length; j < length; j++) {
                const cityItem = data[i].getCityVOList[j]
                cityItem.checked = '' // 市的选中状态
              }
            }
          }
          this.areaList = data
        }
        this.getFreight()
      })
    },
    // 获取运费模板详情
    getFreight() {
      if (this.routeData && this.routeData.templateId) {
        freightApi.getFreight({ templateId: this.routeData.templateId }).then(({ data, code }) => {
          if (code === 200) {
            this.detail.name = data.name
            this.detail.templateId = data.templateId
            this.parseNoDelivery(data.notCityIdList, data.notProvinceIdList, data.notShippedArea)
            if (!data.goodsFreightTemplateRuleVOList.length) return
            for (let i = 0, length = data.goodsFreightTemplateRuleVOList.length; i < length; i++) {
              const { goodsFreightTemplateConditionVO: row, goodsFreightTemplateConfigurationVO: config, templateRuleId } = data.goodsFreightTemplateRuleVOList[i]
              const {freightTemplateConfigurationReqVO,freightTemplateConditionReqVOList } = this.parseRule(row, config, templateRuleId)
              this.detail.goodsFreightTemplateRuleAddVOList.push({freightTemplateConfigurationReqVO, freightTemplateConditionReqVOList, templateRuleId})
              this.goodsFreightTemplateVOList.push({
                freightTemplateConfigurationReqVO: this.filterEdit(freightTemplateConfigurationReqVO),
                freightTemplateConditionReqVOList,
                templateRuleId
              })
            }
            this.copyNoDelivery = JSON.stringify(this.detail.noDeliveryVOList)
            this.copyGoodsFreightTemplate = JSON.stringify(this.goodsFreightTemplateVOList)
            this.copyName = data.name
          }
        })
      }
      this.hasSubmit = false
    },
    // 模板名称
    inputName({ detail }) {
      this.detail.name = detail.value
    },
    // 添加运费规则--打开选择省市弹出层
    openArea() {
      this.areaType = 0
      if (this.detail.goodsFreightTemplateRuleAddVOList.length > 10) {
        return uni.showToast({ title: '最多只能添加10条运费规则', icon: 'none', duration: 2000 })
      }
      this.timeTamp = Date.now()
      this.copyAreaList = JSON.stringify(this.areaList)
      this.dlAreaPopup = true
    },
    // 运费规则--打开选择省市弹出层
    areaOpen(item, index) {
      this.areaType = 0
      if (item.timeTamp) {
        this.timeTamp = item.timeTamp
      } else {
        this.timeTamp = item.templateRuleId
      }
      this.frIndex = index
      this.areaIds = JSON.parse(JSON.stringify(this.detail.goodsFreightTemplateRuleAddVOList[index].freightTemplateConditionReqVOList))
      // 计算已经选择的市的数量
      for (let i = 0, length = this.areaIds.length; i < length; i++) {
        const sub = this.areaIds[i]
        if (sub.cityIdList && isArray(sub.cityIdList)) {
          this.editConfig._selectedNum += sub.cityIdList.length
        }
      }
      this.editConfig = JSON.parse(JSON.stringify(this.detail.goodsFreightTemplateRuleAddVOList[index].freightTemplateConfigurationReqVO))
      this.copyAreaList = JSON.stringify(this.areaList)
      if (this.routeData.templateId && this.editConfig._isFirst && this.detail.goodsFreightTemplateRuleAddVOList.length) {
        this.editConfig._isFirst = false
        const sum = this.computedIsAllChecked()
        if (sum >= this.allCities) this.editConfig._allSelected = true
      }
      this.dlAreaPopup = true
    },
    // 运费规则--打开运费设置
    openSetItem(item) {
      this.editConfig = JSON.parse(JSON.stringify(item.freightTemplateConfigurationReqVO))
      this.dlSettPopup = true
    },
    // 不发货地区--打开选择省市弹出层
    noOpenArea() {
      this.areaType = 1
      this.timeTamp = this.noDelivery.timeTamp
      this.areaIds = JSON.parse(JSON.stringify(this.detail.noDeliveryVOList))
      const sum = this.noDelivery._selectedNum + this.computedIsAllChecked()
      if (sum >= this.allCities) this.noDelivery._allSelected = true
      this.copyAreaList = JSON.stringify(this.areaList)
      this.copyNoDeliver = JSON.stringify(this.noDelivery)
      this.dlAreaPopup = true
    },
    // 关闭选择地址
    closeArea() {
      setTimeout(() => {
        this.areaIds = []
        this.timeTamp = ''
        this.areaList = JSON.parse(this.copyAreaList)
      }, 250)
      if (this.areaType === 0) { // 运费规则关闭的
        if (this.frIndex !== -1) {
          this.detail.goodsFreightTemplateRuleAddVOList[this.frIndex].freightTemplateConfigurationReqVO._isFirst = false
          this.frIndex = -1
        }
      } else { // 不发货地区关闭的
        setTimeout(() => {
          this.noDelivery._isFirst = false
          this.noDelivery = JSON.parse(this.copyNoDeliver)
        },250)
      }
      this.dlAreaPopup = false
    },
    // 省份的选中状态切换
    provinceChecked(item) {
      // this.changeCollapse(item)
      if (item.allChecked && !item.checkeds.includes(this.timeTamp)) return

      const { pKey, cKey, key } = this.getTargetKey(this.areaType)

      let originArea = this[key]._areas
      // 匹配 运费规则中的选中的中文省份市
      let { indexZh, targetZh } = this.getCurrentChina(originArea, item)

      const createArea = {
        provinceStr: '',
        citiesStr: [],
        hasAll: false
      }

      if (item.checkeds.length) {
        const { selectedObj, selectedIx } = this.getCurrentIds(item.id)

        if (item.indeterminate) {
          const citiesId = []
          let originArea = []
          originArea = this[key]._areas
          const citiesStr = []
          let { targetZh: targetStr } = this.getCurrentChina(originArea, item)

          if (!item.checkeds.includes(this.timeTamp)) item.checkeds.push(this.timeTamp)

          for (let i = 0, length = item.getCityVOList.length; i < length; i++) {
            const sub = item.getCityVOList[i]
            if (!sub.checked) {

              sub.checked = this.timeTamp
              ++this[key]._selectedNum

              if (selectedObj) {
                if (!selectedObj[cKey].includes(sub.id)) selectedObj[cKey].push(sub.id)
              } else {
                citiesId.push(sub.id)
              }
              if (targetStr) {
                if (targetStr && isArray(targetStr.citiesStr) && !targetStr.citiesStr.includes(sub.name)) targetStr.citiesStr.push(sub.name)
                if (targetStr.citiesStr.length >= item.getCityVOList.length) targetStr.hasAll = true
              } else {
                citiesStr.push(sub.name)
              }

            }
          }

          if (citiesId.length) {
            this.areaIds.push({
              [cKey]: citiesId,
              [pKey]: item.id
            })
          }
          if (citiesStr.length) {
            originArea.push({
              provinceStr: item.name,
              citiesStr: citiesStr,
              hasAll: citiesStr.length >= item.getCityVOList.length ? true : false
            })
          }
          item.indeterminate = false
          item.allChecked = true
        } else {
          // 有选中的状态
          let sum = 0 // 记录当前给该运费规则选中的个数

          for (let i = 0, length = item.getCityVOList.length; i < length; i++) {
            const sub = item.getCityVOList[i]
            if (sub.checked && sub.checked === this.timeTamp) {
              ++sum
              sub.checked = ''
              --this[key]._selectedNum

              if (selectedObj) {
                selectedObj[cKey] = selectedObj[cKey].filter(el => el !== sub.id)
              }

              if (targetZh && indexZh >= 0) { // 匹配到的
                if (isArray(targetZh.citiesStr)) {
                  targetZh.citiesStr = targetZh.citiesStr.filter(el => el !== sub.name)
                }
              } else { // 未匹配到
                if (!createArea.provinceStr) createArea.provinceStr = item.name
                createArea.citiesStr.push(sub.name)
              }
            }
          }

          createArea.hasAll = false
          // 删除该项
          if (sum >= item.getCityVOList.length && indexZh >= 0) {
            if (this.areaType === 0) {
              this.editConfig._areas.splice(indexZh, 1)
            } else {
              this.noDelivery._areas.splice(indexZh, 1)
            }
          }

          // 根据cityIdList的长度判断是否需要添加删除该项
          if (selectedObj && !selectedObj[cKey].length && selectedIx >= 0) {
            this.areaIds.splice(selectedIx, 1)
          }
          // 根据sum判断该省份是否是半选状态
          if (sum === item.getCityVOList.length) {
            item.indeterminate  = false
          } else {
            item.indeterminate = true
          }
          // 删除checkeds中的timeTamp
          item.checkeds = item.checkeds.filter(el => el !== this.timeTamp)
          item.allChecked = false
        }
        this[key]._allSelected = false
      } else {
        // 无选中状态
        item.checkeds.push(this.timeTamp)
        item.allChecked = true
        if (item.indeterminate) item.indeterminate = false
        // 选中的省市对象{cityIdList: [], provinceId: ''}
        const selectedObj = {
          [cKey]: [],
          [pKey]: item.id
        }
        for (let i = 0, length = item.getCityVOList.length; i < length; i++) {
          const sub = item.getCityVOList[i]
          if (!sub.checked) {
            sub.checked = this.timeTamp
            ++this[key]._selectedNum
            selectedObj[cKey].push(sub.id)
            if (targetZh && indexZh >= 0) { // 匹配到的
              if (isArray(targetZh.citiesStr)) {
                targetZh.citiesStr = targetZh.citiesStr.filter(el => el !== sub.name)
              }
            } else { // 未匹配到
              if (!createArea.provinceStr) createArea.provinceStr = item.name
              createArea.citiesStr.push(sub.name)
              createArea.hasAll = true
            }
          }
        }
        this.areaIds.push(selectedObj)
        if (this.areaIds.length >= this.areaList.length) {
          this[key]._allSelected = true
        }
        // this[key]._allSelected = false
      }

      if (createArea.provinceStr) {
        if (this.areaType === 0) {
          this.editConfig._areas.push(createArea)
        } else {
          this.noDelivery._areas.push(createArea)
        }
      }
    },
    // 市状态切换
    cityChecked(city, cityIx, province, provinceIx) {
      if (city.checked && city.checked !== this.timeTamp) return

      const { pKey, cKey, key } = this.getTargetKey(this.areaType)
      if (city.checked) { // 取消选中

        // 1、该市取消选中状态；
        // 2、改变对应省份的状态；
        for (let i = 0, length = this.areaIds.length; i < length; i++) {
          const sub = this.areaIds[i]
          if (sub[pKey] === province.id) {
            sub[cKey] = sub[cKey].filter(el=>el!==city.id)
            province.allChecked = false
            province.indeterminate = true
            if (!sub[cKey].length) {
              province.checkeds = province.checkeds.filter(el=>el!==this.timeTamp)
              this.areaIds.splice(i, 1)
            }
            if (!province.checkeds.length) province.indeterminate = false
            break
          }
        }

        let originArea = this[key]._areas

        for (let i = 0, length = originArea.length; i < length; i++) {
          const sub = originArea[i]
          if (sub.provinceStr === province.name) {
            sub.hasAll = false
            sub.citiesStr = sub.citiesStr.filter(el=>el!==city.name)
            if (!sub.citiesStr.length) {
              originArea.splice(i, 1)
            }
            break
          }
        }
        --this[key]._selectedNum
        city.checked = ''
        this[key]._allSelected = false
      } else {
        city.checked = this.timeTamp

        let hasCreateId = true
        for (let i = 0, length = this.areaIds.length; i < length; i++) {
          const sub = this.areaIds[i]
          if (sub[pKey] === province.id) {
            hasCreateId = false
            if (!sub[cKey].includes(city.id)) sub[cKey].push(city.id)
            if (sub[cKey].length >= province.getCityVOList.length) {
              province.indeterminate = false
              province.allChecked = true
            }
            break
          }
        }
        if (hasCreateId) {
          province.checkeds.push(this.timeTamp)
          province.indeterminate = true
          if (province.getCityVOList.length === 1) {
            province.indeterminate = false
            province.allChecked = true
          }
          this.areaIds.push({
            [pKey]: province.id,
            [cKey]: [city.id]
          })
        }

        let originArea = this[key]._areas
        let hasCreateStr = true

        for (let i = 0; i < originArea.length; i++) {
          const sub = originArea[i]
          if (sub.provinceStr === province.name) {
            hasCreateStr = false
            if (!sub.citiesStr.includes(city.name)) sub.citiesStr.push(city.name)
            if (sub.citiesStr.length >= province.getCityVOList.length) sub.hasAll = true
          }
        }
        if (hasCreateStr) {
          originArea.push({
            hasAll: province.getCityVOList.length === 1,
            provinceStr: province.name,
            citiesStr: [city.name]
          })
        }
        ++this[key]._selectedNum

        // 更改省份的状态
        let sum = 0
        for (let i = 0, length = province.getCityVOList.length; i < length; i++) {
          const sub = province.getCityVOList[i]
          if (sub.checked) ++sum
        }
        if (sum >= province.getCityVOList.length) {
          province.allChecked = true
          province.indeterminate = false
        }

      }
    },
    // 点击省右箭头-->展开\收起市
    changeCollapse(item) {
      if (!item.height && !item.show) {
        this.$nextTick(() => {this.getUNavbarHeight("#c_" + item.id).then(res => {item.height = res.height})})
      }
      item.show = !item.show
    },
    // 全选选中省市
    allSelected() {
      const { pKey, cKey, key } = this.getTargetKey(this.areaType)
      if (this[key]._allSelected) { // 取消全选

        this.areaIds = []
        this[key]._allSelected = false
        this[key]._areas = []
        this[key]._selectedNum = 0
        for (let i = 0, length = this.areaList.length; i < length; i++) {
          const province = this.areaList[i]
          let sum = 0
          if (province.checkeds.includes(this.timeTamp)) {
            province.checkeds = province.checkeds.filter(el=>el!==this.timeTamp)
            province.allChecked = false
            for (let j = 0, length = province.getCityVOList.length; j < length; j++) {
              const city = province.getCityVOList[j]
              if (city.checked && city.checked === this.timeTamp) {
                ++sum
                city.checked = ''
              }
            }
            if (sum >= province.getCityVOList.length) {
              province.indeterminate = false
            } else {
              province.indeterminate = true
            }
          }
        }

      } else {
        const _areas = []
        const areaIds = []
        for (let i = 0, length = this.areaList.length; i < length; i++) {
          const item = this.areaList[i]
          const createIds = {
            [pKey]: '',
            [cKey]: []
          }
          const createStr = {
            provinceStr: '',
            citiesStr: [],
            hasAll: true
          }
          for (let j = 0, length = item.getCityVOList.length; j < length; j++) {
            const sub = item.getCityVOList[j]
            if (!sub.checked) {
              ++this[key]._selectedNum
              sub.checked = this.timeTamp
              if (!createIds[pKey]) createIds[pKey] = item.id
              createIds[cKey].push(sub.id)
              if (!createStr.provinceStr) createStr.provinceStr = item.name
              createStr.citiesStr.push(sub.name)
              if (createStr.citiesStr.length < item.getCityVOList.length) createStr.hasAll = false
              if (!item.checkeds.includes(this.timeTamp)) item.checkeds.push(this.timeTamp)
              if (!item.allChecked) item.allChecked = true
              if (item.indeterminate) item.indeterminate = false
            }
          }
          if (createIds[pKey]) areaIds.push(createIds)
          if(createStr.provinceStr) _areas.push(createStr)
        }
        this[key]._areas = _areas
        this.areaIds = areaIds
        this[key]._allSelected = true

      }
    },
    // 选择地址--弹出运费设置popup
    openSetting() {
      const { key } = this.getTargetKey(this.areaType)
      if (this[key]._selectedNum <= 0) {
        return uni.showToast({
          title: '请选择城市',
          icon: 'none',
          duration: 2000
        })
      }
      if (this.areaType === 0) {
        this.dlSettPopup = true
      } else {
        this.detail.noDeliveryVOList = JSON.parse(JSON.stringify(this.areaIds))
        this.areaIds = []
        this.dlAreaPopup = false
      }
    },
    // 固定运费、按键计费切换
    changType(type) {
      if (this.editConfig.type === type) return
      this.editConfig.type = this.editConfig.type == 1 ? 0 : 1
    },
    // 指定条件包邮--满件|满元切换
    changeConType(type) {
      const conditionType = this.editConfig.conditionType
      if (conditionType == type) return
      this.editConfig.conditionType = conditionType == 1 ? 2 : 1
    },
    // input输入--只能为数字
    changeInput({detail}, key) {
      this.editConfig[key] = detail.value
    },
    // 重置固定运费|按件计费数据
    resetType() {
      const type = this.editConfig.type
      if (type == 0) { // 重置按件计费数据
        this.editConfig.firstCompany = ''
        this.editConfig.firstPrice = ''
        this.editConfig.continuedCompany = ''
        this.editConfig.continuedPrice = ''
      } else { // 重置固定运费
        this.editConfig.fixedPrice = ''
      }
    },
    // 指定条件包邮开关
    changeFree(val) {
      if (val === 1 && this.editConfig.conditionType === 0) {
        this.editConfig.conditionType = 1
      } else if (val === 0) {
        this.editConfig.conditionType = 0
      }
      this.editConfig.isFree = val
    },
    // 重置指定条件包邮-->满足件数|满足金额
    resetSpecReq() {
      const conditionType = this.editConfig.conditionType
      if (conditionType == 1) { // 重置满足金额
        this.editConfig.conditionMoney = ''
      } else { // 重置满足件数
        this.editConfig.conditionNumber = ''
      }
    },
    // 重置editConfig
    resetEditConfig() {
      this.editConfig.conditionMoney = '' // 满足金额
      this.editConfig.conditionNumber = '' // 满足件数
      this.editConfig.conditionType = 0 // 指定条件（1.满足件数 2.满足金额)
      this.editConfig.continuedCompany = '' // 续个(件)
      this.editConfig.continuedPrice = '' // 续个(件)价格
      this.editConfig.firstCompany = '' // 首个(件)
      this.editConfig.firstPrice = '' // 首个(件)价格
      this.editConfig.fixedPrice = '' // 固定价格
      this.editConfig.isFree = 0 // 指定条件包邮 0:否 1：是
      this.editConfig.type = 0 // 计费规则 0：固定运费 1：按件计费
      this.editConfig._areas = [] // 自定义用于展示选中的省份市中文
      this.editConfig._selectedNum = 0 // 当前选中市的总条数
    },
    // 运费设置【确定】
    submitSetting() {
      // 计费规则 0：固定运费 1：按件计费
      const reg = /^([0-9]*)$/
      if (this.editConfig.type === 0) {
        if (this.editConfig.fixedPrice === '') {
          this.showToast('请输入运费金额')
          return
        } else if (!reg.test(this.editConfig.fixedPrice)) {
          this.showToast('请输入整数运费金额')
          return
        }
      } else {
        const { firstCompany, firstPrice, continuedCompany, continuedPrice } = this.editConfig
        if (firstCompany === '' || firstPrice === '' || continuedCompany === '' || continuedPrice === '') {
          this.showToast('请输入按件计费条件')
          return
        } else if (!reg.test(firstCompany)||!reg.test(firstPrice)||!reg.test(continuedCompany)||!reg.test(continuedPrice)) {
          this.showToast('请输入整数按件计费条件')
          return
        }
      }
      if (this.editConfig.isFree === 1) {
        const { conditionType, conditionNumber, conditionMoney } = this.editConfig
        if (conditionType === 1 && (conditionNumber === '' || !reg.test(conditionNumber))) {
          this.showToast('请输入整数包邮件数')
          return
        } else if (conditionType === 2 && (conditionMoney === '' || !reg.test(conditionMoney))) {
          this.showToast('请输入整数包邮金额')
          return
        }
      }
      this.dlAreaPopup = false
      this.dlSettPopup = false
      this.resetType()
      this.resetSpecReq()
      const copyAreaIds = JSON.parse(JSON.stringify(this.areaIds))
      const copyEdit = JSON.parse(JSON.stringify(this.editConfig))
      if (this.frIndex >= 0) { // 编辑
        this.detail.goodsFreightTemplateRuleAddVOList[this.frIndex].freightTemplateConditionReqVOList = copyAreaIds
        this.detail.goodsFreightTemplateRuleAddVOList[this.frIndex].freightTemplateConfigurationReqVO = copyEdit
        this.goodsFreightTemplateVOList[this.frIndex].freightTemplateConditionReqVOList = copyAreaIds
        this.goodsFreightTemplateVOList[this.frIndex].freightTemplateConfigurationReqVO = this.filterEdit(copyEdit)
      } else { // 新增
        this.detail.goodsFreightTemplateRuleAddVOList.push({
          timeTamp: this.timeTamp,
          freightTemplateConditionReqVOList: copyAreaIds,
          freightTemplateConfigurationReqVO: copyEdit
        })
        this.goodsFreightTemplateVOList.push({
          freightTemplateConditionReqVOList: copyAreaIds,
          freightTemplateConfigurationReqVO: this.filterEdit(copyEdit)
        })
      }
      this.resetEditConfig()
      this.areaIds = []
      this.timeTamp = ''
      this.frIndex = -1
    },
    // 保存设置
    onSubmit() {
      if (this.detail.name.trim() === '') {
        this.showToast('请输入运费模板名称')
        return
      }
      if (this.dlModal) this.dlModal = false
      if (this.routeData.templateId) { // 修改
        this.hasSubmit = true
        freightApi.update({
          goodsFreightTemplateRuleUpdateVOList: this.goodsFreightTemplateVOList,
          name: this.detail.name,
          noDeliveryVOList: this.detail.noDeliveryVOList,
          templateId: this.detail.templateId
        }).then(res => {
          if (res.code === 200) {
            this.showToast('修改成功')
            setTimeout(() => {
              this.navigateBack()
            }, 1500)
          }
        }).catch(() => {
          this.hasSubmit = false
          this.showToast('网络超时')
        })

      } else { // 新增
        this.hasSubmit = true
        freightApi.create({
          goodsFreightTemplateRuleAddVOList: this.goodsFreightTemplateVOList,
          name: this.detail.name,
          noDeliveryVOList: this.detail.noDeliveryVOList,
        }).then(res => {
          if (res.code === 200) {
            this.showToast('新增成功')
            setTimeout(() => {
              this.navigateBack()
            }, 1500)
          }
        }).catch(() => {
          this.hasSubmit = false
          this.showToast('网络超时')
        })
      }
    },
    // 获取指定key
    getTargetKey(type) {
      const targetKeys = {
        pKey: 'provinceId',
        cKey: 'cityIdList',
        key: 'editConfig'
      }
      if (type === 1) {
        targetKeys.pKey = 'notProvinceId'
        targetKeys.cKey = 'notCityIdList'
        targetKeys.key = 'noDelivery'
      }
      return targetKeys
    },
    // 匹配当前选中的中文省市对象及下标
    getCurrentChina(array, province) {
      let indexZh = -1
      let targetZh = null
      for (let i = 0, length = array.length; i < length; i++) {
        const sub = array[i]
        if (sub.provinceStr === province.name) {
          indexZh = i
          targetZh = sub
          break
        }
      }
      return { indexZh, targetZh }
    },
    // 匹配当前选中的区域id对象及下标
    getCurrentIds(provinceId) {
      const { pKey } = this.getTargetKey(this.areaType)
      const res = {
        selectedObj: null,
        selectedIx: -1
      }
      for (let i = 0, length = this.areaIds.length; i < length; i++) {
        const sub = this.areaIds[i]
        if (sub[pKey] === provinceId) {
          res.selectedObj = sub
          res.selectedIx = i
          break
        }
      }
      return res
    },
    // 处理不发货地区
    parseNoDelivery(notCityIds, notProvinceIds, notAreas) {
      // 处理选中的省市中文
      const areas = notAreas.split('|')
      if (areas.length) {
        for (let i = 0, length = areas.length; i < length; i++) {
          const itemArea = areas[i]
          const target = this.parseProvinceCityChina(itemArea)
          this.noDelivery._selectedNum += target.citiesStr.length
          const province = this.areaList.find(row=>row.name===target.provinceStr)
          if (province && target.citiesStr.length >= province.getCityVOList.length) target.hasAll = true
          this.noDelivery._areas.push(target)
        }
      }
      // 处理id
      if (notProvinceIds.length) {
        this.detail.noDeliveryVOList = this.parseProvinceCityId(notProvinceIds, notCityIds, this.noDelivery.timeTamp, 'notProvinceId', 'notCityIdList')
      }
    },
    // 处理运费规则
    parseRule(row, config, templateRuleId) {
      const freightTemplateConfigurationReqVO = {
        ...config,
        _selectedNum: 0,
        _areas: [],
        _allSelected: false,
        _isFirst: true
      }
      // 处理选中的省市中文
      const areas = row.conditionArea.split('|')
      if (areas.length) {
        for (let i = 0, length = areas.length; i < length; i++) {
          const itemArea = areas[i]
          const target = this.parseProvinceCityChina(itemArea)
          freightTemplateConfigurationReqVO._selectedNum += target.citiesStr.length
          const province = this.areaList.find(row=>row.name===target.provinceStr)
          if (province && target.citiesStr.length >= province.getCityVOList.length) target.hasAll = true
          freightTemplateConfigurationReqVO._areas.push(target)
        }
      }
      // 处理id
      const freightTemplateConditionReqVOList = this.parseProvinceCityId(row.provinceIdList, row.cityIdList, templateRuleId, 'provinceId', 'cityIdList')
      return {freightTemplateConfigurationReqVO, freightTemplateConditionReqVOList}
    },
    // 数组化选中的省市中文名称
    parseProvinceCityChina(itemArea) {
      const target = { provinceStr: '', citiesStr: [], hasAll: false }
      const offset = itemArea.indexOf('(')
      if (offset !== -1) target.provinceStr = itemArea.slice(0, offset)
      const matchArray = itemArea.match(/\((.+?)\)/gi) // 过滤省份中文名称
      let cityStr = ''
      if (matchArray.length) cityStr = matchArray[0].replace(/[\(|\)]/gi, '') // 过滤()
      target.citiesStr = cityStr.split(',')
      return target
    },
    // 对象数组化选中的省市id
    parseProvinceCityId(provinceIds, cityIds, timeTamp, pKey, cKey) {
      const resArray = []
      for (let i = 0, length = provinceIds.length; i < length; i++) {
        const provinceId = provinceIds[i]
        const target = { [pKey]: provinceId, [cKey]: [] }
        // 使用省份id的前两位数字匹配对应的市
        const offsetCity = provinceId.toString().slice(0, 2)
        // 对城市列表进行标识
        const provinceRow = this.areaList.find(row=>row.id === provinceId)
        let sum = 0
        for (let j = 0, length = cityIds.length; j < length; j++) {
          const cityId = cityIds[j]
          if (cityId.toString().indexOf(offsetCity) !== -1) {
            target[cKey].push(cityId)
          }
          if (provinceRow) {
            provinceRow.indeterminate = true
            if (!provinceRow.checkeds.includes(timeTamp)) provinceRow.checkeds.push(timeTamp)
            for (let k = 0, length = provinceRow.getCityVOList.length; k < length; k++) {
              const cityRow = provinceRow.getCityVOList[k]
              if (cityRow.id === cityId) {
                cityRow.checked = timeTamp
                ++sum
              }
            }
            if (sum >= provinceRow.getCityVOList.length) {
              provinceRow.allChecked = true
              provinceRow.indeterminate = false
            }
          }
        }
        resArray.push(target)
      }
      return resArray
    },
    filterEdit(config) {
      const obj = {}
      const filterKeys = ['_areas', '_selectedNum', '_allSelected']
      for (const key in config) {
        if (!filterKeys.includes(key)) { obj[key] = config[key] }
      }
      return obj
    },
    // 计算当前的全选状态
    computedIsAllChecked() {
      let sum = 0
      for (let i = 0, length = this.detail.goodsFreightTemplateRuleAddVOList.length; i < length; i++) {
        const { freightTemplateConfigurationReqVO } = this.detail.goodsFreightTemplateRuleAddVOList[i]
        // console.log(freightTemplateConfigurationReqVO)
        sum += freightTemplateConfigurationReqVO._allSelected
      }
      return sum
    },
    showToast(title) {
      uni.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "editTemplate.scss";
</style>
